from datetime import time

from django.db.models import QuerySet
from django.shortcuts import render, redirect
from alipay import AliPay
from rest_framework import mixins, viewsets
from rest_framework.authentication import SessionAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

from goods.models import Goods
from trade.serializers import OrderSerializer, OrderDetailSerializer, OrderGoodsSerialzier
from trade.utils import ali_init
import time
# Create your views here.
from django.utils import timezone, cache
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet

from taotao import settings

from trade.models import OrderInfo, OrderGoods
from user.authentications import JsonWebTokenAuthentication


class OrderViewset(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin,
                   viewsets.GenericViewSet):
    """
    订单管理
    list:
        获取个人订单
    delete:
        删除订单
    create：
        新增订单
    """
    # permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JsonWebTokenAuthentication,)
    serializer_class = OrderSerializer

    # 动态配置serializer
    def get_serializer_class(self):
        if self.action == "retrieve":
            return OrderDetailSerializer
        if self.action == "list":
            return OrderGoodsSerialzier
        return OrderSerializer

    # 获取订单列表
    def get_queryset(self):
        if self.action == "list":
            #订单信息列表需要显示商品信息
            orders = OrderInfo.objects.filter(user=self.request.user)  # .values('id')#.select_related('good')
            order_goods = QuerySet(model=OrderGoods)
            for order in orders:
                order_goods = order_goods.union(OrderGoods.objects.filter(order=order))
            return order_goods
        return OrderInfo.objects.filter(user=self.request.user)

    def perform_create(self, serializer):
        order = serializer.save()
        good = Goods.objects.filter(id=self.request.data.get('goods_id'))[0]
        order_goods = OrderGoods()
        order_goods.goods = good
        order_goods.order = order
        order_goods.save()
        return order


class AliPayBackViewSet(APIView):
    def get(self, request):
        """
        处理支付宝的return_url返回
        """
        processed_dict = {}
        # 1. 获取GET中参数
        for key, value in request.GET.items():
            processed_dict[key] = value
        # 2. 取出sign
        sign = processed_dict.pop("sign", None)

        # 3. 生成ALipay对象
        alipay = ali_init()

        verify_re = alipay.verify(processed_dict, sign)

        # 这里可以不做操作。因为不管发不发return url。notify url都会修改订单状态。
        if verify_re is True:
            order_sn = processed_dict.get('out_trade_no', None)
            trade_no = processed_dict.get('trade_no', None)
            trade_status = processed_dict.get('trade_status', None)

            existed_orders = OrderInfo.objects.filter(order_sn=order_sn)
            for existed_order in existed_orders:
                existed_order.pay_status = trade_status
                existed_order.trade_no = trade_no
                existed_order.pay_time = timezone.now()
                existed_order.save()

            response = redirect("/index/#/app/home/member/order")
            return response

        else:
            response = redirect("index")
            return response

    def post(self, request):
        """
        处理支付宝的notify_url
        """
        # 存放post里面所有的数据
        processed_dict = {}
        # 取出post里面的数据
        for key, value in request.POST.items():
            processed_dict[key] = value
        # 把signpop掉，文档有说明
        sign = processed_dict.pop("sign", None)

        # 生成一个Alipay对象
        alipay = ali_init()
        # 进行验证
        verify_re = alipay.verify(processed_dict, sign)

        # 如果验签成功
        if verify_re is True:
            # 商户网站唯一订单号
            order_sn = processed_dict.get('out_trade_no', None)
            # 支付宝系统交易流水号
            trade_no = processed_dict.get('trade_no', None)
            # 交易状态
            trade_status = processed_dict.get('trade_status', None)

            # 查询数据库中订单记录
            existed_orders = OrderInfo.objects.filter(order_sn=order_sn)
            for existed_order in existed_orders:
                # # 订单商品项
                # order_goods = existed_order.goods.all()
                # # 商品销量增加订单中数值
                # for order_good in order_goods:
                #     goods = order_good.goods
                #     goods.sold_num += order_good.goods_num
                #     goods.save()

                # 更新订单状态
                existed_order.pay_status = trade_status
                existed_order.trade_no = trade_no
                existed_order.pay_time = timezone.now()
                existed_order.save()
            # 需要返回一个'success'给支付宝，如果不返回，支付宝会一直发送订单支付成功的消息
            return Response("success")

